/*
 * Segue Audio Player
 * Copyright 2011 Fraser McCrossan frasermccrossan@gmail.com
 * 
 * This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published
 *  by the Free Software Foundation, either version 3 of the License,
 *  or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

package com.frasermccrossan.segue;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.BaseColumns;
import android.provider.MediaStore.Audio.AudioColumns;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.frasermccrossan.segue.providers.QueueProvider;

public class BrowseRecentlyPlayed extends FragmentActivity
	implements OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {

	public static final String TAG = "BrowseRecentlyPlayed";

	SimpleCursorAdapter mAdapter;
	
	ListView recentView;
	Cursor recentCursor = null;
	
	QueuePlayer mQueuePlayer = null;
	boolean mIsBound;
	
	ContentResolver cr;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cr = getContentResolver();
        setContentView(R.layout.recently_played);
        
        recentView = (ListView)findViewById(R.id.previous_list);
        recentView.setOnItemClickListener(this);
        registerForContextMenu(recentView);
        mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, null,
                new String[] { AudioColumns.TITLE, AudioColumns.ARTIST },
                new int[] { android.R.id.text1, android.R.id.text2 },
                0);
        recentView.setAdapter(mAdapter);
        startService(new Intent(this, QueuePlayer.class));
        getSupportLoaderManager().initLoader(0, null, this);
    }
        
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mQueuePlayer = ((QueuePlayer.QueueBinder)service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {
            mQueuePlayer = null;
        }
    };

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.  This
        // sample only has one Loader, so we don't care about the ID.
        // First, pick the base URI to use depending on whether we are
        // currently filtering.
        Uri baseUri = QueueProvider.CONTENT_URI;

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        return new CursorLoader(this, baseUri,
                				new String [] { BaseColumns._ID, QueueProvider.ORDER, AudioColumns.TITLE, AudioColumns.ARTIST, AudioColumns.ALBUM },
                				QueueProvider.ORDER + "<?",
                				new String[] { QueueProvider.CURRENT_TRACK.toString() },
                				QueueProvider.ORDER + " desc");
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Swap the new cursor in.  (The framework will take care of closing the
        // old cursor once we return.)
    	try {
    		mAdapter.swapCursor(data);
    	}
    	catch (Exception e) {
    		Log.i(TAG, "onLoadFinished(): " + e.getMessage());    		
    	}
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
        mAdapter.swapCursor(null);
    }

    @Override
    public void onStart() {
    	super.onStart();
    	mIsBound = bindService(new Intent(this, QueuePlayer.class), mConnection, Context.BIND_AUTO_CREATE);
    }

//    @Override
//    public void onResume() {
//    	super.onResume();
//    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.add_track_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.prefs:
            gotoPreferences();
            return true;
        case R.id.clear_queue:
        	mQueuePlayer.clearQueue();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (parent == recentView) {
			// this works because previous tracks are in the list starting at -1 and descending
			mQueuePlayer.addPreviousTrack(QueueProvider.CURRENT_TRACK - 1 - position);
		}
	}
	
//	@Override
//	public void onCreateContextMenu(ContextMenu menu, View v,
//	                                ContextMenuInfo menuInfo) {
//	  super.onCreateContextMenu(menu, v, menuInfo);
//	  AdapterView.AdapterContextMenuInfo listItemInfo = (AdapterView.AdapterContextMenuInfo)menuInfo;
//	  int item = listItemInfo.position;
//	  Cursor c = cr.query(QueueProvider.CONTENT_URI,
//			  new String[] { MediaStore.Audio.Media.TITLE },
//			  QueueProvider.ORDER + "=?",
//			  new String[] { Integer.toString(listItemInfo.position) },
//			  null);
//	  String title = "";
//	  if (c != null) {
//		  if (c.moveToFirst()) {
//			  title = c.getString(0);
//		  }
//		  c.close();
//	  }
//	  if (item == QueueProvider.CURRENT_TRACK) {
//		  menu.setHeaderTitle(String.format(getString(R.string.current_track), title));
//		  menu.add(ContextMenu.NONE, SKIP_FORWARD, 10, getString(R.string.skip_forward));
//		  menu.add(ContextMenu.NONE, SKIP_BACKWARD, 20, getString(R.string.skip_backward));
//		  menu.add(ContextMenu.NONE, PLAY_LATER, 30, getString(R.string.play_later));
//		  menu.add(ContextMenu.NONE, REMOVE_ALL_BY_ARTIST, 40, getString(R.string.remove_others_by));
//		  menu.add(ContextMenu.NONE, REMOVE_ALL_IN_ALBUM, 50, getString(R.string.remove_others_in));		  
//	  }
//	  else {
//		  menu.setHeaderTitle(String.format("%d. %s", item, title));
//		  if (item > QueueProvider.NEXT_TRACK) {
//			  menu.add(ContextMenu.NONE, PLAY_NEXT, 1, getString(R.string.play_next));
//		  }
//		  menu.add(ContextMenu.NONE, REMOVE_TRACK, 1, getString(R.string.remove_track));
//		  menu.add(ContextMenu.NONE, REMOVE_ALL_BY_ARTIST, 2, getString(R.string.remove_all_by));
//		  menu.add(ContextMenu.NONE, REMOVE_ALL_IN_ALBUM, 3, getString(R.string.remove_all_in));
//	  }
//	}
//	
//	@Override
//	public boolean onContextItemSelected(MenuItem item) {
//	  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
//	  switch (item.getItemId()) {
//	  case REMOVE_TRACK:
//	    mQueuePlayer.delTrack(info.position);
//	    return true;
//	  case REMOVE_ALL_BY_ARTIST:
//		    mQueuePlayer.delByArtist(info.position);
//		    return true;
//	  case REMOVE_ALL_IN_ALBUM:
//		    mQueuePlayer.delByAlbum(info.position);
//		    return true;
//	  case SKIP_FORWARD:
//			mQueuePlayer.playSkip();
//			return true;
//	  case SKIP_BACKWARD:
//			mQueuePlayer.playSkipBack();
//			return true;
//	  case PLAY_LATER:
//			mQueuePlayer.playLater(info.position);
//			return true;
//	  case PLAY_NEXT:
//			mQueuePlayer.playNext(info.position);
//			return true;
//	  default:
//	    return super.onContextItemSelected(item);
//	  }
//	}
			
    void gotoPreferences() {
    	Intent prefs = new Intent(BrowseRecentlyPlayed.this, MainPreferences.class);
    	startActivity(prefs);
    }
    
//    @Override
//    protected void onPause() {
//    	stopStatusTask();
//    	super.onPause();
//    }
    
    @Override
    protected void onStop() {
        if (mIsBound) {
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
        }
    	super.onStop();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}